package com.mlm.mlmapp.utils;

import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Environment;
import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

import com.androidquery.AQuery;
import com.androidquery.callback.AjaxCallback;
import com.androidquery.util.Constants;
import com.mlm.mlmapp.adapter.view.AQProgressDialog;

import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class CommonUtils {
    public static final String IMAGE_FILE_NAME = "comment.jpg";

    public static void postRequest(String url, AQuery aq,
                                   AjaxCallback<JSONObject> cb, List<NameValuePair> pairs) {
        String sign = MsgDigestUtil.getDigestParam(pairs);
        // make digest sign str
        pairs.add(new BasicNameValuePair("sign", sign));
        HttpEntity entity = null;
        try {
            entity = new UrlEncodedFormEntity(pairs, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        Map<String, Object> params = new HashMap<String, Object>();

        params.put(Constants.POST_ENTITY, entity);
        // execute request
        aq.progress(new AQProgressDialog(aq.getContext())).ajax(url, params, JSONObject.class,
                cb);

    }
    public static boolean isNetworkConnected(Context context) {
        if (context != null) {
            ConnectivityManager mConnectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo mNetworkInfo = mConnectivityManager.getActiveNetworkInfo();
            if (mNetworkInfo != null) {
                return mNetworkInfo.isAvailable();
            }
        }
        return false;
    }
    public static boolean isEmojiCharacter(char codePoint) {
        return (codePoint == 0x0) ||
                (codePoint == 0x9) ||
                (codePoint == 0xA) ||
                (codePoint == 0xD) ||
                ((codePoint >= 0x20) && (codePoint <= 0xD7FF)) ||
                ((codePoint >= 0xE000) && (codePoint <= 0xFFFD)) ||
                ((codePoint >= 0x10000) && (codePoint <= 0x10FFFF));
    }

    public static boolean containsEmoji(String source) {
        int len = source.length();
        for (int i = 0; i < len; i++) {
            char codePoint = source.charAt(i);
            if (!isEmojiCharacter(codePoint)) { //如果不能匹配,则该字符是Emoji表情
                return true;
            }
        }
        return false;
    }

    /**
     * 密码匹配，以字母开头，长度 在6-18之间，只能包含字符、数字和下划线。
     *
     * @param pwd
     * @return
     */
    public static boolean isCorrectUserPwd(String pwd) {
        Pattern p = Pattern.compile("^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,16}$");
        Matcher m = p.matcher(pwd);
        System.out.println(m.matches() + "-pwd-");
        return m.matches();
    }

    /**
     * 手机号码格式匹配
     *
     * @param mobiles
     * @return
     */
    public static boolean isMobileNO(String mobiles) {
        Pattern p = Pattern
                .compile("^1(3[0-9]|4[57]|5[0-35-9]|8[0-9]|70)\\d{8}$");

        Matcher m = p.matcher(mobiles);
        System.out.println(m.matches() + "-telnum-");
        return m.matches();
    }

    /**
     * <p>
     * 将文件转成base64 字符串
     * </p>
     *
     * @param path 文件路径
     * @return
     * @throws Exception
     */
    public static String encodeBase64File(String path) throws Exception {
        File file = new File(path);
        FileInputStream inputFile = new FileInputStream(file);
        byte[] buffer = new byte[(int) file.length()];
        inputFile.read(buffer);
        inputFile.close();
        String temp = Base64.encodeToString(buffer, Base64.DEFAULT);
        file.delete();
        return temp;
    }

    public static String saveBitmap(Bitmap photo) {
        Log.e("liub", "保存图片");
        File f = new File("/sdcard/", System.currentTimeMillis() + ".png");
        if (f.exists()) {
            f.delete();
        }
        try {
            FileOutputStream out = new FileOutputStream(f);
            photo.compress(Bitmap.CompressFormat.PNG, 90, out);
            out.flush();
            out.close();
            Log.i("liub", "已经保存");
            return f.getAbsolutePath();
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return f.getAbsolutePath();
    }

    public static void postRequest4Array(String url, AQuery aq,
                                         AjaxCallback<JSONArray> cb, List<NameValuePair> pairs) {
        String sign = MsgDigestUtil.getDigestParam(pairs);
        // make digest sign str
        pairs.add(new BasicNameValuePair("sign", sign));
        HttpEntity entity = null;
        try {
            entity = new UrlEncodedFormEntity(pairs, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        Map<String, Object> params = new HashMap<String, Object>();

        params.put(Constants.POST_ENTITY, entity);

        // execute request
        aq.progress(new AQProgressDialog(aq.getContext())).ajax(url, params, JSONArray.class,
                cb);
    }

    public static boolean validateETEmpty(Context con, List<View> list) {
        for (View v : list) {
            EditText et = (EditText) v;
            if (et.getText().length() <= 0) {
                Toast.makeText(con, "[" + et.getHint() + "]", Toast.LENGTH_SHORT)
                        .show();
                return false;
            }
            if (et.getTag() != null && "phone".equals(et.getTag().toString())
                    && et.getText().length() != 11) {
                Toast.makeText(con, "[" + "请输入正确格式的手机号码" + "]",
                        Toast.LENGTH_SHORT).show();
                return false;
            }

        }
        return true;
    }

    public static int dip2px(Context context, float dipValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dipValue * scale + 0.5f);
    }

    public static int px2dip(Context context, float pxValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (pxValue / scale + 0.5f);
    }

    public static Drawable setButtonDrawableRight(Context context, int resid) {
        Drawable d;
        Resources res = context.getResources();
        d = res.getDrawable(resid);
        // 调用setCompoundDrawables时，必须调用Drawable.setBounds()方法,否则图片不显示
        d.setBounds(0, 0, d.getMinimumWidth(), d.getMinimumHeight());
        return d;
    }

    public static int sp2px(Context context, float spValue) {
        final float fontScale = context.getResources().getDisplayMetrics().scaledDensity;
        return (int) (spValue * fontScale + 0.5f);
    }

    /**
     * 裁剪图片方法实现
     *
     * @param uri
     */
    public static Intent startPhotoZoom(Uri uri) {
        if (uri == null) {
            Log.i("tag", "The uri is not exist.");
        }
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        // 设置裁剪
        intent.putExtra("crop", "true");
        // aspectX aspectY 是宽高的比例
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        // outputX outputY 是裁剪图片宽高
        intent.putExtra("outputX", 320);
        intent.putExtra("outputY", 320);
        intent.putExtra("return-data", true);
        return intent;
    }

    public static String getPhotoFileName() {
        Date date = new Date(System.currentTimeMillis());
        SimpleDateFormat dateFormat = new SimpleDateFormat(
                "'IMG'_yyyy-MM-dd HH:mm:ss");
        return dateFormat.format(date) + ".png";

    }

    public static String getURLStringParams(String url,
                                            HashMap<String, String> params) {

        StringBuilder sb = new StringBuilder(url);
        sb.append("?");
        for (String key : params.keySet()) {
            sb.append(key);
            sb.append("=");
            sb.append(params.get(key));
            sb.append("&");
        }
        if ('&' == sb.charAt(sb.length() - 1)) {
            sb.deleteCharAt(sb.length() - 1);
        }

        return sb.toString();

    }

    public static String getJsonString(JSONObject obj, String key) {
        String res = "";
        try {
            if (!obj.isNull(key))
                res = obj.getString(key);
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return res;
    }

    public static JSONObject getJsonObject(JSONObject obj, String key) {
        JSONObject res = null;
        try {
            if (!obj.isNull(key))
                res = obj.getJSONObject(key);
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return res;
    }

    public static int getJsonInt(JSONObject obj, String key) {
        int res = 0;
        try {
            if (!obj.isNull(key))
                res = obj.getInt(key);
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return res;
    }

    public static JSONArray getJsonArray(JSONObject obj, String key) {
        JSONArray res = null;
        try {
            if (!obj.isNull(key))
                res = obj.getJSONArray(key);
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return res;
    }

    public static void sendBroadCast(Context con, String action, String flag, String flagvalue) {
        Intent intent = new Intent();
        intent.setAction(action);
        intent.putExtra(flag, flagvalue);
        con.sendOrderedBroadcast(intent, null);
    }

    public static Uri getAvatarUri() {
        File tempFile = new File(Environment.getExternalStorageDirectory(),
                IMAGE_FILE_NAME);
        if (!tempFile.exists()) {
            try {
                tempFile.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return Uri.fromFile(tempFile);
    }

    private final static String APP_FOLDER = "MLM";

    public static File createFile(String mFileName) {
        File sdcardDir = Environment.getExternalStorageDirectory();
        File folder = new File(sdcardDir
                + File.separator + APP_FOLDER);
        if (!folder.exists()) {
            //创建存放目录
            folder.mkdir();
        }
        File saveFilePath = new File(folder, mFileName);
        return saveFilePath;

    }

    public static void openFile(Context context, Uri uri) {
        // TODO Auto-generated method stub
        Intent intent = new Intent();
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setAction(android.content.Intent.ACTION_VIEW);
        intent.setDataAndType(uri,
                "application/vnd.android.package-archive");
        context.startActivity(intent);
    }
}
